﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using YookingBizWQW.Class.Credit.mp;
using YookingBizWQW.Class.Credit.pub;
using YookingBizWQW.Class.Public;
using YookingDBNormal.Class;
using YookingFileIO.Class;
using YookingKitBox.Class.Public;
using YookingSvrDBCall.Class.DBLogic;
using YookingSvrDBCall.Class.DBPub;

namespace YookingBizWQW.Class.Credit.pc
{
    public class clsTradeOrder_Xzd
    {
        //注释：王庆文 2020年12月14日=========================================================================
        //还款计划保存成功之后，需要为该计划设置N条刷卡、还款交易订单记录（用于提交到银行支付接口）。
        //根据UnitCode、PersonCode、PlanID查询还款计划，然后为该还款计划生成N条用于跟银行对接的交易订单记录。
        //向库表XYK_TradeOrder中写入记录。
        public string CreateRepayTradeOrder(string strB64RequestData)
        {
            string strRtData = "no data";

            //先进行解密，然后在进行中文解码，最后得到明文的请求数据
            string strRequestData = clsHandleData.DeUrlRequest(strB64RequestData);

            #region 将strRequestData包含的各种参数一一解析出来

            string strUnitCode = "CHN000"; //平台编码
            string strPersonCode = "0000"; //人员编码
            string strPlanID = "00000000"; //计划ID
            string strPlanType = "POS";    //计划类型：POS=信用卡代还，ATM=信用卡套现，HBEI=花呗代还 

            //这些参数用★分隔开，客户端与服务器端要一致
            string[] strArray = strRequestData.Split('★');
            if (strArray.Length >= 4)
            {
                strUnitCode = strArray[0];
                strPersonCode = strArray[1];
                strPlanID = strArray[2];
                strPlanType = strArray[3];
            }

            #endregion

            //将刚刚保存入库的总计划信息查询出来（只有一条符合条件的记录）
            clsTradeOrder_New myPlan = new clsTradeOrder_New(); //实例化类库
            DataSet dsPlan = myPlan.GetRepayPlanInfo(strUnitCode, strPersonCode, strPlanID);

            if (strPlanType == "POS") //创建多条代还交易记录
            {
                strRtData = CreatePOSTradeOrder(dsPlan);
            }

            if (strPlanType == "ATM") //创建一条套现交易记录
            {
                strRtData = CreateATMTradeOrder(dsPlan);
            }

            return strRtData; //交易订单的处理结果
        }

        #region 生成N条POS信用卡代还交易订单

        //注释：王庆文 2020年12月14日=========================================================================
        //创建多条代还交易记录
        public string CreatePOSTradeOrder(DataSet dsPlan)
        {
            int iShuaKOrderCount = 0; //总共生成了几笔刷卡订单
            int iHuanKOrderCount = 0; //总共生成了几笔还款订单

            if (dsPlan != null && dsPlan.Tables.Count > 0 && dsPlan.Tables[0].Rows.Count > 0)
            {
                DataTable dtPlan = dsPlan.Tables[0];

                #region 将DataSet中的字段值全部解析出来，以备后面的逻辑使用

                string strUnitCode = dtPlan.Rows[0]["UNITCODE"].ToString();           //平台编码 
                string strPersonCode = dtPlan.Rows[0]["PERSONCODE"].ToString();       //制定人员 
                string strPlanID = dtPlan.Rows[0]["PLANID"].ToString();               //计划ID 
                string strPlanType = dtPlan.Rows[0]["PLANTYPE"].ToString();           //计划类型：POS=信用卡代还，ATM=信用卡套现，HBEI=花呗代还 
                string strPlanTime = dtPlan.Rows[0]["PLANTIME"].ToString();           //制定时间 
                string strEnBankCardNo = dtPlan.Rows[0]["BANKCARDNO"].ToString();     //信用卡卡号（密文） 
                string strPlanAmount = dtPlan.Rows[0]["PLANAMOUNT"].ToString();       //计划金额 
                string strPlanDateBegin = dtPlan.Rows[0]["PLANDATEBEGIN"].ToString(); //开始日期 
                string strPlanDateEnd = dtPlan.Rows[0]["PLANDATEEND"].ToString();     //截止日期 
                string strPayCityCodSet = dtPlan.Rows[0]["PAYCITY"].ToString();       //预设消费城市,310000,310100,310112 
                string strPlanState = dtPlan.Rows[0]["PLANSTATE"].ToString();         //计划状态 
                string strMemberLevel = dtPlan.Rows[0]["MEMBERLEVEL"].ToString();     //会员级别 
                string strOtherMemo = dtPlan.Rows[0]["OTHERMEMO"].ToString();         //还款计划总表中的其他说明 

                #endregion

                int iDays = 0; //完成本次代还业务一共需要几天的时间
                double dRowAmt = 0; //随机生成的单次交易金额
                double dRowAmtSum = 0; //随机交易额总和
                double dPlanAmount = Convert.ToDouble(strPlanAmount); //用户要求的还款金额
                if (dPlanAmount <= 990) //小额还款低于990元，一天内先刷卡、再还款即可完成任务
                {
                    //确定订单交易日期
                    string strTradeDate = strPlanDateBegin.Replace(" 00:00:00", ""); 

                    //先生成一条刷卡交易订单，交易时间在上午
                    bool bPos01Ret = Create_POS01_ShuaKa_TradeOrder(strUnitCode, strPersonCode, strPlanID, strEnBankCardNo, strTradeDate, strPayCityCodSet, dPlanAmount);
                    if (bPos01Ret)
                    {
                        iShuaKOrderCount = 1; //刷卡订单数累计
                    }

                    //再生成一条还款交易订单，交易时间在下午
                    bool bPos02Ret = Create_POS02_HuanKuan_TradeOrder(strUnitCode, strPersonCode, strPlanID, strEnBankCardNo, strTradeDate, strPayCityCodSet, dPlanAmount);
                    if (bPos02Ret)
                    {
                        iHuanKOrderCount = 1; //还款订单数累计 
                    }

                    UpdatePlanEndDate(strUnitCode, strPlanID, strTradeDate); //重置一下还款计划的截至时间
                }
                else
                {
                    do //小额还款高于990元，需要N天才能完成全部代还款任务
                    {
                        #region 在690元~990元之间随机生成一个还款交易金额

                        //生成m,n之间的整型随机数
                        Random rdNumber = new Random();
                        int iIntPart = rdNumber.Next(690, 990); //金额的整数部分
                        int iDotPart = rdNumber.Next(0, 99); //金额的小数部分

                        //在指定数值范围内随机生成订单交易金额，
                        //统一设置成保留小数点后两位的格式。
                        string strIntPart = iIntPart.ToString();
                        string strDotPart = iDotPart.ToString();
                        string strTradeAmount = strIntPart + "." + strDotPart;

                        #endregion

                        #region 随机交易金额计算及临界值金额修正

                        dRowAmt = Convert.ToDouble(strTradeAmount); //本笔要创建的订单金额
                        dRowAmtSum = dRowAmtSum + dRowAmt; //已经创建完成的订单金额累计
                        if (dRowAmtSum > dPlanAmount)
                        {
                            double dOffsetValue = dRowAmtSum - dPlanAmount;
                            dRowAmt = dRowAmt - dOffsetValue; //将多出来的交易金额修正掉

                            dRowAmtSum = dRowAmtSum - dOffsetValue; //重新计算修正累计金额
                        }

                        #endregion

                        #region 计算出本次要创建的订单的交易日期，格式为：yyyy-MM-dd

                        //计算出订单的交易日期
                        DateTime dtPlanDateBegin = Convert.ToDateTime(strPlanDateBegin);
                        DateTime dtTradeDate = dtPlanDateBegin.AddDays(iDays); //yyyy-MM-dd
                        string strTradeDate = dtTradeDate.ToString("yyyy-MM-dd");

                        iDays = iDays + 1; //iDays ++ 日期往后调一天 

                        #endregion

                        //先生成一条刷卡交易订单，交易时间在上午
                        bool bPos01Ret = Create_POS01_ShuaKa_TradeOrder(strUnitCode, strPersonCode, strPlanID, strEnBankCardNo, strTradeDate, strPayCityCodSet, dRowAmt);
                        if (bPos01Ret)
                        {
                            iShuaKOrderCount += 1; //刷卡订单数累计
                        }

                        //再生成一条还款交易订单，交易时间在下午
                        bool bPos02Ret = Create_POS02_HuanKuan_TradeOrder(strUnitCode, strPersonCode, strPlanID, strEnBankCardNo, strTradeDate, strPayCityCodSet, dRowAmt);
                        if (bPos02Ret)
                        {
                            iHuanKOrderCount += 1; //还款订单数累计 
                        }

                        UpdatePlanEndDate(strUnitCode, strPlanID, strTradeDate); //重置一下还款计划的截至时间
                    }
                    while (dPlanAmount > dRowAmtSum); //循环条件设置
                }
            }

            return "【刷出订单" + iShuaKOrderCount + "笔】【还款订单" + iHuanKOrderCount + "笔】";
        }

        //注释：王庆文 2020年12月14日=====================================================================================
        //生成一条刷卡交易订单，交易时间在上午
        public bool Create_POS01_ShuaKa_TradeOrder(string strUnitCode, string strPersonCode, string strPlanID,
                              string strEnBankCardNo, string strTradeDate, string strPayCityCodSet, double dTradeAmt)
        {
            #region 相对为固定值的基础参数

            //生成平台交易订单号
            Random rd = new Random(); //随机数实例
            int iRandom = rd.Next(100000, 999999); //生成六位随机数
            string strCurTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            //订单号格式示例：POS0120200502225459620954773
            string strPOrderNum = "POS01" + strCurTime + iRandom.ToString();

            //信用卡对应的预留手机号
            clsTradeOrder_New myPlan = new clsTradeOrder_New(); //实例化函数类库
            string strTrMobilePhone = myPlan.GetCreditCardPhone(strUnitCode, strPersonCode, strEnBankCardNo);

            //根据省份代码，判断如果为直辖市，则省份代码即为城市代码
            string strPayCity = strPayCityCodSet; //默认的交易商户所在城市代码
            string strPayProvince = strPayCityCodSet.Substring(0, 6);
            if (strPayProvince == "110000" || strPayProvince == "310000"
                || strPayProvince == "120000" || strPayProvince == "500000")
            {
                strPayCity = strPayProvince; //直接取前六位作为城市代码
            }
            else
            {
                //取中间六位作为城市代码
                strPayCity = strPayCityCodSet.Substring(7, 6);
            }

            //随机生成订单的交易时间
            int iHour = rd.Next(10, 12);
            int iMinute = rd.Next(10, 59);
            int iSecond = rd.Next(10, 59);
            string strTradeTime = strTradeDate + " " + iHour + ":" + iMinute + ":" + iSecond;

            //刷卡金额X = (用户填写的还款金额Amt 990元 + 3元) / (1-0.6%)
            double dServiceRate = 0.0060;
            double dMoneySum = (dTradeAmt + 3) / (1 - dServiceRate);
            dMoneySum = Math.Round(dMoneySum, 2); //保留小数点后两位
            dMoneySum = dMoneySum + 0.01; //为了防止还款时余额刚好差一点点，保险起见，统一多刷1分钱出来

            //计算出本次刷卡需要收取的服务费金额          
            double dServiceFee = dServiceRate * dMoneySum;
            dServiceFee = Math.Round(dServiceFee, 2); //保留小数点后两位

            #endregion

            #region 交易订单表XYK_TradeOrder入库需要的全部字段

            //string strPlanID = strPlanID;                           //计划ID
            string strTradeType = "POS01";                            //交易类型
            string strTradeTo = "01";                                 //资金流向，01=支出、02=收入
            //string strPOrderNum = strPOrderNum;                     //平台订单号
            string strIOrderNum = strPOrderNum;                       //接口订单号
            string strTrBankCardNo = strEnBankCardNo;                 //交易银行卡号          
            //string strTrMobilePhone = strTrMobilePhone;             //交易预留手机号
            string strPlanTradeTime = strTradeTime;                   //预设交易时间
            string strTradeAmount = dTradeAmt.ToString("0.00");       //交易金额
            string strTradeServiceRate = dServiceRate.ToString("0.0000"); //手续费比率
            string strTradeServiceFee = dServiceFee.ToString("0.00"); //手续费金额
            string strMemberDiscount = "1";                           //手续费折扣
            string strRealServiceRate = strTradeServiceRate;          //实收手续比率
            string strRealServiceFee = strTradeServiceFee;            //实收手续费
            string strExtraServiceFee = "1.50";                       //额外收费金额
            string strMoneySum = dMoneySum.ToString("0.00");          //最终交易金额
            string strAllServiceFee = (dServiceFee + 1.50).ToString("0.00"); //服务收费总额
            //string strPayCity = strPayCity;                         //预设消费城市
            string strMccList = "";                                   //交易MCC码
            string strSeBankCardNo = strEnBankCardNo;                 //结算银行卡号
            string strSeMobilePhone = strTrMobilePhone;               //结算预留手机号
            string strInterCallTime = "";                             //接口调用时间
            string strRealTradeTime = "";                             //实际交易时间
            string strRealTradeState = "99";                          //实际交易状态
            string strRealSettTime = "";                              //实际结算时间
            string strRealSettState = "99";                           //实际结算状态
            string strOtherMemo = "";                                 //订单交易表中的其他说明

            #endregion

            #region 生成即将写入数据库的json数组

            JArray objJArray = new JArray();
            JObject objJObject = new JObject();
            objJObject.Add("PlanID", strPlanID);
            objJObject.Add("TradeType", strTradeType);
            objJObject.Add("TradeTo", strTradeTo);
            objJObject.Add("POrderNum", strPOrderNum);
            objJObject.Add("IOrderNum", strIOrderNum);
            objJObject.Add("TrBankCardNo", strTrBankCardNo);
            objJObject.Add("TrMobilePhone", strTrMobilePhone);
            objJObject.Add("PlanTradeTime", strPlanTradeTime);
            objJObject.Add("TradeAmount", strTradeAmount);
            objJObject.Add("TradeServiceRate", strTradeServiceRate);
            objJObject.Add("TradeServiceFee", strTradeServiceFee);
            objJObject.Add("MemberDiscount", strMemberDiscount);
            objJObject.Add("RealServiceFee", strRealServiceFee);
            objJObject.Add("RealServiceRate", strRealServiceRate);
            objJObject.Add("ExtraServiceFee", strExtraServiceFee);
            objJObject.Add("AllServiceFee", strAllServiceFee);
            objJObject.Add("MoneySum", strMoneySum);
            objJObject.Add("PayCity", strPayCity);
            objJObject.Add("MccList", strMccList);
            objJObject.Add("SeBankCardNo", strSeBankCardNo);
            objJObject.Add("SeMobilePhone", strSeMobilePhone);
            objJObject.Add("InterCallTime", strInterCallTime);
            objJObject.Add("RealTradeTime", strRealTradeTime);
            objJObject.Add("RealTradeState", strRealTradeState);
            objJObject.Add("RealSettTime", strRealSettTime);
            objJObject.Add("RealSettState", strRealSettState);
            objJObject.Add("OtherMemo", strOtherMemo);

            objJArray.Add(objJObject);

            #endregion

            #region 向数据库中写入交易订单数据

            //clsRWFile myLog = new clsRWFile(); //将请求结果保存到txt文件中
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", objJArray.ToString(), false);

            DataSet dsData = clsJConvert.JArryToDataSet(objJArray.ToString()); //将Json数组转成DataSet

            clsShare myDict = new clsShare(); //根据人员编码，得到人员ID的值
            string strUserName = myDict.GetNewColValue("Data", "SA_ORG_PERSONINFO", "PERSONCODE", strPersonCode, "PERSONID");

            clsWriteDB myWrite = new clsWriteDB(); //先判断数据是否存在，根据判断结果自动执行insert或者update
            string strKeyColSet = "PlanID,PlanTradeTime,TradeAmount"; //重值判断
            string strPos01Result = myWrite.WriteDBNormal_UseSYSCol("Data", "XYK_TradeOrder", strKeyColSet, strUserName, dsData);

            #endregion

            //POS01刷卡订单记录insert成功
            if (!(strPos01Result.Contains("yooking null"))) 
            {
                return true; //成功标记
            }
            else
            {
                return false; //失败标记
            }
        }

        //注释：王庆文 2020年12月14日===================================================================================
        //生成一条还款交易订单，交易时间在下午
        public bool Create_POS02_HuanKuan_TradeOrder(string strUnitCode, string strPersonCode, string strPlanID,
                              string strEnBankCardNo, string strTradeDate, string strPayCityCodSet, double dTradeAmt)
        {
            #region 相对为固定值的基础参数

            //生成平台交易订单号
            Random rd = new Random(); //随机数实例
            int iRandom = rd.Next(100000, 999999); //生成六位随机数
            string strCurTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            //订单号格式示例：POS0220200502225459620954773
            string strPOrderNum = "POS02" + strCurTime + iRandom.ToString();

            //信用卡对应的预留手机号
            clsTradeOrder_New myPlan = new clsTradeOrder_New(); //实例化函数类库
            string strTrMobilePhone = myPlan.GetCreditCardPhone(strUnitCode, strPersonCode, strEnBankCardNo);

            //根据省份代码，判断如果为直辖市，则省份代码即为城市代码
            string strPayCity = strPayCityCodSet; //默认的交易商户所在城市代码
            string strPayProvince = strPayCityCodSet.Substring(0, 6);
            if (strPayProvince == "110000" || strPayProvince == "310000"
                || strPayProvince == "120000" || strPayProvince == "500000")
            {
                strPayCity = strPayProvince; //直接取前六位作为城市代码
            }
            else
            {
                //取中间六位作为城市代码
                strPayCity = strPayCityCodSet.Substring(7, 6);
            }

            //随机生成订单的交易时间
            int iHour = rd.Next(14, 18);
            int iMinute = rd.Next(10, 59);
            int iSecond = rd.Next(10, 59);
            string strTradeTime = strTradeDate + " " + iHour + ":" + iMinute + ":" + iSecond;

            //刷卡金额X = (用户填写的还款金额Amt 990元 + 3元) / (1-0.6%)
            double dPos01Rate = 0.0060;
            double dPos01Sum = (dTradeAmt + 3) / (1 - dPos01Rate);
            dPos01Sum = Math.Round(dPos01Sum, 2); //保留小数点后两位
            dPos01Sum = dPos01Sum + 0.01; //为了防止还款时余额刚好差一点点，保险起见，统一多刷1分钱出来

            //计算出本次刷卡需要收取的服务费金额          
            double dPos01Fee = dPos01Rate * dPos01Sum;
            dPos01Fee = Math.Round(dPos01Fee, 2); //保留小数点后两位

            //还入金额Y = 刷卡金额X - 刷卡时的手续费金额M - 3.00
            double dMoneySum = dPos01Sum - dPos01Fee - 3.00;

            #endregion

            #region 交易订单表XYK_TradeOrder入库需要的全部字段

            //string strPlanID = strPlanID;                  //计划ID
            string strTradeType = "POS02";                   //交易类型
            string strTradeTo = "02";                        //资金流向，01=支出、02=收入
            //string strPOrderNum = strPOrderNum;            //平台订单号
            string strIOrderNum = strPOrderNum;              //接口订单号
            string strTrBankCardNo = strEnBankCardNo;        //交易银行卡号          
            //string strTrMobilePhone = strTrMobilePhone;    //交易预留手机号
            string strPlanTradeTime = strTradeTime;          //预设交易时间
            string strTradeAmount = dTradeAmt.ToString("0.00"); //交易金额
            string strTradeServiceRate = "0.0000";           //手续费比率
            string strTradeServiceFee = "0.00";              //手续费金额
            string strMemberDiscount = "1";                  //手续费折扣
            string strRealServiceRate = "0.0000";            //实收手续比率
            string strRealServiceFee = "0.00";               //实收手续费
            string strExtraServiceFee = "1.50";              //额外收费金额
            string strMoneySum = dMoneySum.ToString("0.00"); //最终交易金额
            string strAllServiceFee = "1.50";                //服务收费总额
            //string strPayCity = strPayCity;                //预设消费城市
            string strMccList = "";                          //交易MCC码
            string strSeBankCardNo = strEnBankCardNo;        //结算银行卡号
            string strSeMobilePhone = strTrMobilePhone;      //结算预留手机号
            string strInterCallTime = "";                    //接口调用时间
            string strRealTradeTime = "";                    //实际交易时间
            string strRealTradeState = "99";                 //实际交易状态
            string strRealSettTime = "";                     //实际结算时间
            string strRealSettState = "99";                  //实际结算状态
            string strOtherMemo = "";                        //订单交易表中的其他说明

            #endregion

            #region 生成即将写入数据库的json数组

            JArray objJArray = new JArray();
            JObject objJObject = new JObject();
            objJObject.Add("PlanID", strPlanID);
            objJObject.Add("TradeType", strTradeType);
            objJObject.Add("TradeTo", strTradeTo);
            objJObject.Add("POrderNum", strPOrderNum);
            objJObject.Add("IOrderNum", strIOrderNum);
            objJObject.Add("TrBankCardNo", strTrBankCardNo);
            objJObject.Add("TrMobilePhone", strTrMobilePhone);
            objJObject.Add("PlanTradeTime", strPlanTradeTime);
            objJObject.Add("TradeAmount", strTradeAmount);
            objJObject.Add("TradeServiceRate", strTradeServiceRate);
            objJObject.Add("TradeServiceFee", strTradeServiceFee);
            objJObject.Add("MemberDiscount", strMemberDiscount);
            objJObject.Add("RealServiceFee", strRealServiceFee);
            objJObject.Add("RealServiceRate", strRealServiceRate);
            objJObject.Add("ExtraServiceFee", strExtraServiceFee);
            objJObject.Add("AllServiceFee", strAllServiceFee);
            objJObject.Add("MoneySum", strMoneySum);
            objJObject.Add("PayCity", strPayCity);
            objJObject.Add("MccList", strMccList);
            objJObject.Add("SeBankCardNo", strSeBankCardNo);
            objJObject.Add("SeMobilePhone", strSeMobilePhone);
            objJObject.Add("InterCallTime", strInterCallTime);
            objJObject.Add("RealTradeTime", strRealTradeTime);
            objJObject.Add("RealTradeState", strRealTradeState);
            objJObject.Add("RealSettTime", strRealSettTime);
            objJObject.Add("RealSettState", strRealSettState);
            objJObject.Add("OtherMemo", strOtherMemo);

            objJArray.Add(objJObject);

            #endregion

            #region 向数据库中写入交易订单数据

            //clsRWFile myLog = new clsRWFile(); //将请求结果保存到txt文件中
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", objJArray.ToString(), false);

            DataSet dsData = clsJConvert.JArryToDataSet(objJArray.ToString()); //将Json数组转成DataSet

            clsShare myDict = new clsShare(); //根据人员编码，得到人员ID的值
            string strUserName = myDict.GetNewColValue("Data", "SA_ORG_PERSONINFO", "PERSONCODE", strPersonCode, "PERSONID");

            clsWriteDB myWrite = new clsWriteDB(); //先判断数据是否存在，根据判断结果自动执行insert或者update
            string strKeyColSet = "PlanID,PlanTradeTime,TradeAmount"; //重值判断
            string strPos02Result = myWrite.WriteDBNormal_UseSYSCol("Data", "XYK_TradeOrder", strKeyColSet, strUserName, dsData);

            #endregion

            //POS02还款订单记录insert成功
            if (!(strPos02Result.Contains("yooking null")))
            {
                return true; //成功标记
            }
            else
            {
                return false; //失败标记
            }
        }

        //注释：王庆文 2020年12月14日=======================================================================
        //重置一下还款计划的截至时间
        public void UpdatePlanEndDate(string strUnitCode, string strPlanID, string strDateValue)
        {
            string strPlanDateEnd = strDateValue + " 23:59:59";

            StringBuilder sbUpdateSQL = new StringBuilder();
            sbUpdateSQL.AppendLine(" update XYK_REPAYPLAN set ");
            sbUpdateSQL.AppendLine("   PlanDateEnd='" + strPlanDateEnd + "' "); //计划截止时间
            sbUpdateSQL.AppendLine(" where " + clsSQLSyntax.IsNullSQL("Data", "SYS_CANCELDATETIME"));
            sbUpdateSQL.AppendLine("   and UnitCode='" + strUnitCode + "' ");
            sbUpdateSQL.AppendLine("   and PlanID='" + strPlanID + "' ");

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化数据库操作类
            myDB.YookingExecuteNonQuery("Data", sbUpdateSQL.ToString()); //更新计划执行状态
        }

        #endregion

        #region 生成一条ATM信用卡套现交易订单

        //注释：王庆文 2020年12月14日============================================================
        //创建一条ATM信用卡套现交易订单，一次性提取现金
        public string CreateATMTradeOrder(DataSet dsPlan)
        {
            int iATMOrderCount = 0; //ATM套现订单总数

            if (dsPlan != null && dsPlan.Tables.Count > 0 && dsPlan.Tables[0].Rows.Count > 0)
            {
                DataTable dtPlan = dsPlan.Tables[0];

                #region 将DataSet中的字段值全部解析出来，以备后面的逻辑使用

                string strUnitCode = dtPlan.Rows[0]["UNITCODE"].ToString();           //平台编码 
                string strPersonCode = dtPlan.Rows[0]["PERSONCODE"].ToString();       //制定人员 
                string strPlanID = dtPlan.Rows[0]["PLANID"].ToString();               //计划ID 
                string strPlanType = dtPlan.Rows[0]["PLANTYPE"].ToString();           //计划类型：POS=信用卡代还，ATM=信用卡套现，HBEI=花呗代还 
                string strPlanTime = dtPlan.Rows[0]["PLANTIME"].ToString();           //制定时间 
                string strEnBankCardNo = dtPlan.Rows[0]["BANKCARDNO"].ToString();     //信用卡卡号（密文） 
                string strPlanAmount = dtPlan.Rows[0]["PLANAMOUNT"].ToString();       //计划金额 
                string strPlanDateBegin = dtPlan.Rows[0]["PLANDATEBEGIN"].ToString(); //开始日期 
                string strPlanDateEnd = dtPlan.Rows[0]["PLANDATEEND"].ToString();     //截止日期 
                string strPayCityCodSet = dtPlan.Rows[0]["PAYCITY"].ToString();       //预设消费城市,310000,310100,310112 
                string strPlanState = dtPlan.Rows[0]["PLANSTATE"].ToString();         //计划状态 
                string strMemberLevel = dtPlan.Rows[0]["MEMBERLEVEL"].ToString();     //会员级别 
                //string strOtherMemo = dtPlan.Rows[0]["OTHERMEMO"].ToString();       //还款计划总表中的其他说明 

                #endregion

                #region 相对为固定值的基础参数

                //生成平台交易订单号
                Random rd = new Random(); //随机数实例
                int iRandom = rd.Next(100000, 999999); //生成六位随机数
                string strCurTimeValue = DateTime.Now.ToString("yyyyMMddHHmmssfff");

                //订单号格式示例：ATM0120200502225459620954773
                string strPOrderNum = "ATM01" + strCurTimeValue + iRandom.ToString();

                //信用卡对应的预留手机号
                clsTradeOrder_New myPlan = new clsTradeOrder_New(); //实例化函数类库
                string strTrMobilePhone = myPlan.GetCreditCardPhone(strUnitCode, strPersonCode, strEnBankCardNo);

                //根据省份代码，判断如果为直辖市，则省份代码即为城市代码
                string strPayCity = strPayCityCodSet; //默认的交易商户所在城市代码
                string strPayProvince = strPayCityCodSet.Substring(0, 6);
                if (strPayProvince == "110000" || strPayProvince == "310000"
                    || strPayProvince == "120000" || strPayProvince == "500000")
                {
                    strPayCity = strPayProvince; //直接取前六位作为城市代码
                }
                else
                {
                    //取中间六位作为城市代码
                    strPayCity = strPayCityCodSet.Substring(7, 6);
                }

                //实际到账金额X = 套现金额Amt 500元 - (套现金额Amt 500元* 0.6%) - 3元
                //计算出本次刷卡需要收取的服务费金额
                double dServiceRate = 0.0060; //设置交易费率
                double dServiceFee = dServiceRate * Convert.ToDouble(strPlanAmount);
                dServiceFee = Math.Round(dServiceFee, 2); //保留小数点后两位

                //如果是信用卡套现，则结算卡要填写银行借记卡信息                      
                //查询平台里指定会员的银行借记卡卡号和预留手机号码
                string[] arrySettleCard = myPlan.GetSettleBankCardInfo(strUnitCode, strPersonCode);
                string strSettleCardNo = arrySettleCard[0]; //结算借记卡卡号
                string strSettleCardPhone = arrySettleCard[1]; //借记卡预留手机号码

                #endregion

                #region 交易订单表XYK_TradeOrder入库需要的全部字段

                string strCurTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                //string strPlanID = strPlanID;                           //计划ID
                string strTradeType = "ATM01";                            //交易类型
                string strTradeTo = "02";                                 //资金流向，01=支出、02=收入
                //string strPOrderNum = strPOrderNum;                     //平台订单号
                string strIOrderNum = strPOrderNum;                       //接口订单号
                string strTrBankCardNo = strEnBankCardNo;                 //交易银行卡号          
                //string strTrMobilePhone = strTrMobilePhone;             //交易预留手机号
                string strPlanTradeTime = strCurTime;                     //预设交易时间
                string strTradeAmount = strPlanAmount;                    //交易金额
                string strTradeServiceRate = dServiceRate.ToString("0.0000"); //手续费比率
                string strTradeServiceFee = dServiceFee.ToString("0.00"); //手续费金额
                string strMemberDiscount = "1";                           //手续费折扣
                string strRealServiceRate = strTradeServiceRate;          //实收手续比率
                string strRealServiceFee = strTradeServiceFee;            //实收手续费
                string strExtraServiceFee = "3.00";                       //额外收费金额
                string strMoneySum = strPlanAmount;                       //最终交易金额
                string strAllServiceFee = (dServiceFee + 3.00).ToString("0.00"); //服务收费总额
                //string strPayCity = strPayCity;                         //预设消费城市
                string strMccList = "";                                   //交易MCC码
                string strSeBankCardNo = strSettleCardNo;                 //结算银行卡号
                string strSeMobilePhone = strSettleCardPhone;             //结算预留手机号
                string strInterCallTime = "";                             //接口调用时间
                string strRealTradeTime = "";                             //实际交易时间
                string strRealTradeState = "99";                          //实际交易状态
                string strRealSettTime = "";                              //实际结算时间
                string strRealSettState = "99";                           //实际结算状态
                string strOtherMemo = "";                                 //订单交易表中的其他说明

                #endregion

                #region 生成即将写入数据库的json数组

                JArray objJArray = new JArray();
                JObject objJObject = new JObject();
                objJObject.Add("PlanID", strPlanID);
                objJObject.Add("TradeType", strTradeType);
                objJObject.Add("TradeTo", strTradeTo);
                objJObject.Add("POrderNum", strPOrderNum);
                objJObject.Add("IOrderNum", strIOrderNum);
                objJObject.Add("TrBankCardNo", strTrBankCardNo);
                objJObject.Add("TrMobilePhone", strTrMobilePhone);
                objJObject.Add("PlanTradeTime", strPlanTradeTime);
                objJObject.Add("TradeAmount", strTradeAmount);
                objJObject.Add("TradeServiceRate", strTradeServiceRate);
                objJObject.Add("TradeServiceFee", strTradeServiceFee);
                objJObject.Add("MemberDiscount", strMemberDiscount);
                objJObject.Add("RealServiceFee", strRealServiceFee);
                objJObject.Add("RealServiceRate", strRealServiceRate);
                objJObject.Add("ExtraServiceFee", strExtraServiceFee);
                objJObject.Add("AllServiceFee", strAllServiceFee);
                objJObject.Add("MoneySum", strMoneySum);
                objJObject.Add("PayCity", strPayCity);
                objJObject.Add("MccList", strMccList);
                objJObject.Add("SeBankCardNo", strSeBankCardNo);
                objJObject.Add("SeMobilePhone", strSeMobilePhone);
                objJObject.Add("InterCallTime", strInterCallTime);
                objJObject.Add("RealTradeTime", strRealTradeTime);
                objJObject.Add("RealTradeState", strRealTradeState);
                objJObject.Add("RealSettTime", strRealSettTime);
                objJObject.Add("RealSettState", strRealSettState);
                objJObject.Add("OtherMemo", strOtherMemo);

                objJArray.Add(objJObject);

                #endregion

                #region 向数据库中写入交易订单数据

                //clsRWFile myLog = new clsRWFile(); //将请求结果保存到txt文件中
                //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", objJArray.ToString(), false);

                DataSet dsData = clsJConvert.JArryToDataSet(objJArray.ToString()); //将Json数组转成DataSet

                clsShare myDict = new clsShare(); //根据人员编码，得到人员ID的值
                string strUserName = myDict.GetNewColValue("Data", "SA_ORG_PERSONINFO", "PERSONCODE", strPersonCode, "PERSONID");

                clsWriteDB myWrite = new clsWriteDB(); //先判断数据是否存在，根据判断结果自动执行insert或者update
                string strKeyColSet = "PlanID,PlanTradeTime,TradeAmount"; //重值判断
                string strAtm01Result = myWrite.WriteDBNormal_UseSYSCol("Data", "XYK_TradeOrder", strKeyColSet, strUserName, dsData);

                #endregion

                //ATM01套现订单记录insert成功
                if (!(strAtm01Result.Contains("yooking null")))
                {
                    iATMOrderCount = 1; //成功写入一条ATM套现订单记录
                }
            }

            return "【ATM提现订单" + iATMOrderCount + "笔】";
        }

        #endregion

        #region 注销代还、提现业务订单，或者把交易状态置为失败

        //注释：王庆文 2020年12月16日================================================================================
        //注销交易订单表XYK_TradeOrder的记录，注销交易计划表XYK_RepayPlan的记录
        public string CancelPlanTradeOrder(string strB64RequestData)
        {
            string strRtData = "no data";

            //先进行解密，然后在进行中文解码，最后得到明文的请求数据
            string strRequestData = clsHandleData.DeUrlRequest(strB64RequestData);

            #region 将strRequestData包含的各种参数一一解析出来

            string strUnitCode = "CHN000"; //平台编码
            string strUserName = "000000"; //APP用户名
            string strPlanID = "00000000"; //计划ID

            //这些参数用★分隔开，客户端与服务器端要一致
            string[] strArray = strRequestData.Split('★');
            if (strArray.Length >= 3)
            {
                strUnitCode = strArray[0];
                strUserName = strArray[1];
                strPlanID = strArray[2];
            }

            #endregion

            string strCurTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            #region 删除交易订单的SQL语句

            StringBuilder sbDelTrSQL = new StringBuilder();
            sbDelTrSQL.AppendLine(" update XYK_TradeOrder set ");
            sbDelTrSQL.AppendLine("    SYS_CANCELUSERNAME='" + strUserName + "', ");
            sbDelTrSQL.AppendLine("    SYS_CANCELDATETIME='" + strCurTime + "', ");
            sbDelTrSQL.AppendLine("    SYS_CANCELREASON='用户在APP端主动删除' ");
            sbDelTrSQL.AppendLine(" where PlanID='" + strPlanID + "' ");

            #endregion

            #region 删除交易计划的SQL语句

            StringBuilder sbDelPlSQL = new StringBuilder();
            sbDelPlSQL.AppendLine(" update XYK_RepayPlan set ");
            sbDelPlSQL.AppendLine("    SYS_CANCELUSERNAME='" + strUserName + "', ");
            sbDelPlSQL.AppendLine("    SYS_CANCELDATETIME='" + strCurTime + "', ");
            sbDelPlSQL.AppendLine("    SYS_CANCELREASON='用户在APP端主动删除' ");
            sbDelPlSQL.AppendLine(" where UnitCode='" + strUnitCode + "' ");
            sbDelPlSQL.AppendLine("   and PlanID='" + strPlanID + "' ");

            #endregion

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化类库
            object objTrCount = myDB.YookingExecuteNonQuery("Data", sbDelTrSQL.ToString()); //删除交易子订单
            object objPlCount = myDB.YookingExecuteNonQuery("Data", sbDelPlSQL.ToString()); //更新交易总计划

            strRtData = "已删除计划数【"+ objPlCount.ToString() + "】，已删除订单数【" + objTrCount.ToString() + "】";

            return strRtData; //业务逻辑的处理结果
        }

        //注释：王庆文 2020年12月16日================================================================================
        //将订单表XYK_TradeOrder的交易记录设置为交易失败，将计划表XYK_RepayPlan的计划状态设置为失败
        public string UpdatePlanTradeStatusToFail(string strB64RequestData)
        {
            string strRtData = "no data";

            //先进行解密，然后在进行中文解码，最后得到明文的请求数据
            string strRequestData = clsHandleData.DeUrlRequest(strB64RequestData);

            #region 将strRequestData包含的各种参数一一解析出来

            string strUnitCode = "CHN000"; //平台编码
            string strPlanID = "00000000"; //计划ID

            //这些参数用★分隔开，客户端与服务器端要一致
            string[] strArray = strRequestData.Split('★');
            if (strArray.Length >= 2)
            {
                strUnitCode = strArray[0];
                strPlanID = strArray[1];
            }

            #endregion

            string strCurTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            #region 更新交易订单状态为失败的SQL语句

            StringBuilder sbUpdTrSQL = new StringBuilder();
            sbUpdTrSQL.AppendLine(" update XYK_TradeOrder set ");
            sbUpdTrSQL.AppendLine("   InterCallTime='" + strCurTime + "', "); //接口调用时间
            sbUpdTrSQL.AppendLine("   RealTradeTime='" + strCurTime + "', "); //实际交易时间
            sbUpdTrSQL.AppendLine("   RealTradeState='01', ");                //实际交易状态
            sbUpdTrSQL.AppendLine("   RealSettTime='" + strCurTime + "', ");  //实际结算时间
            sbUpdTrSQL.AppendLine("   RealSettState='01' ");                  //实际结算状态
            sbUpdTrSQL.AppendLine(" where PlanID='" + strPlanID + "' ");

            #endregion

            #region 更新交易计划为失败的SQL语句

            StringBuilder sbUpdPlSQL = new StringBuilder();
            sbUpdPlSQL.AppendLine(" update XYK_RepayPlan set ");
            sbUpdPlSQL.AppendLine("   PlanState='01' "); //计划执行状态
            sbUpdPlSQL.AppendLine(" where UnitCode='" + strUnitCode + "' ");
            sbUpdPlSQL.AppendLine("   and PlanID='" + strPlanID + "' ");

            #endregion

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化类库
            object objTrCount = myDB.YookingExecuteNonQuery("Data", sbUpdTrSQL.ToString()); //重置子订单状态
            object objPlCount = myDB.YookingExecuteNonQuery("Data", sbUpdPlSQL.ToString()); //重置总计划状态

            strRtData = "已失败计划数【" + objPlCount.ToString() + "】，已失败订单数【" + objTrCount.ToString() + "】";

            return strRtData; //业务逻辑的处理结果
        }

        #endregion

        #region 由系统管理员在后台PC端为指定用户的信用卡手工生成一条还款交易订单，以便把用户信用卡虚拟账户中的余额清零

        //注释：王庆文 2020年12月18日=========================================================================
        //  1、先判断该用户信用卡是否有正在执行，或者待执行的订单记录；
        //  2、再生成一条还款计划；
        //  3、再创建一条还款交易订单，交易金额为虚拟账户中的全部余额；
        public string RefundCardBanlance(string strB64RequestData)
        {
            string strRtData = "{\"RESULT\":\"yooking null\"}";

            //先进行解密，然后在进行中文解码，最后得到明文的请求数据
            string strRequestData = clsHandleData.DeUrlRequest(strB64RequestData);

            #region 将strRequestData包含的各种参数一一解析出来

            string strUnitCode = "CHN000"; //平台编码
            string strPersonCode = "0000"; //人员编码
            string strEnBankCardNo = "00"; //信用卡卡号（密文）

            //这些参数用★分隔开，客户端与服务器端要一致
            string[] strArray = strRequestData.Split('★');
            if (strArray.Length >= 3)
            {
                strUnitCode = strArray[0];
                strPersonCode = strArray[1];
                strEnBankCardNo = strArray[2];
            }

            #endregion

            if (CheckOrderIsExist(strEnBankCardNo))
            {
                strRtData = "{\"RESULT\":\"该信用卡存在未执行、或者正在执行中的交易订单，不允许发起临时退款请求！\"}";
            }
            else
            {
                //向丰付的支付通道发起信用卡虚拟账户余额查询请求，查看账户内的总余额数字
                clsInterfaceXzd myZxd = new clsInterfaceXzd(); //类库实例化
                string strBnlceResult = myZxd.QueryUserBanlance(strB64RequestData);
                JObject objBnlceResult = JObject.Parse(strBnlceResult);
                string strBanlance = objBnlceResult["BANLANCE"].ToString();

                double dBanlance = Convert.ToDouble(strBanlance);
                if (dBanlance == 0)
                {
                    strRtData = "{\"RESULT\":\"该信用卡虚拟账户中的资金余额为0元，无法发起退款请求！\"}";
                }
                else if (dBanlance <= 1.50)
                {
                    strRtData = "{\"RESULT\":\"该信用卡虚拟账户中的资金余额少于1.50元，无法支付单次交易的笔数费，不能发起退款请求！\"}";
                }
                else
                {
                    //向数据库中写入还款计划信息、然后再向数据库中写入还款交易订单记录（只写入一条记录）。
                    //将用于虚拟账户余额清零的还款交易订单记录写入到后台数据库中。
                    string strRefundResult = CreateTempRepayPlan(strUnitCode, strPersonCode, strEnBankCardNo, strBanlance);

                    strRtData = "{\"RESULT\":\"" + strRefundResult + "\"}";
                }
            }

            return strRtData; //退款交易订单的处理结果
        }

        //注释：王庆文 2020年06月13日=========================================================================
        //检查和判断当前号码的信用卡是否存在未执行、或者正在执行中的交易订单
        private bool CheckOrderIsExist(string strEnBankCardNo)
        {
            StringBuilder sbQuerySQL = new StringBuilder();
            sbQuerySQL.AppendLine(" SELECT count(1) FROM xyk_tradeorder t ");
            sbQuerySQL.AppendLine(" WHERE " + clsSQLSyntax.IsNullSQL("Data", "t.SYS_CANCELDATETIME"));
            sbQuerySQL.AppendLine(" AND t.RealTradeState != '00' ");
            sbQuerySQL.AppendLine(" AND t.RealTradeState != '01' ");
            sbQuerySQL.AppendLine(" AND t.RealTradeState != '02' ");
            sbQuerySQL.AppendLine(" AND t.TrBankCardNo = '" + strEnBankCardNo + "' ");

            //clsRWFile myLog = new clsRWFile(); //将待执行的SQL语句记录下来
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", sbQuerySQL.ToString());

            clsDbSQLLogic myDB = new clsDbSQLLogic(); //实例化数据库操作类
            object objCount = myDB.YookingGetDataScalar("Data", sbQuerySQL.ToString());

            if (Convert.ToInt32(objCount) > 0)
            {
                return true; //存在未执行、或者正在执行中的交易订单
            }
            else
            {
                return false; //交易订单不存在，或者已经全部执行完毕
            }
        }

        //注释：王庆文 2020年06月13日=================================================================================================
        //向数据库中写入还款计划信息、然后再向数据库中写入还款交易订单记录（只写入一条记录）。
        //将用于虚拟账户余额清零的还款交易订单记录写入到后台数据库中。
        private string CreateTempRepayPlan(string strDefUnitCode, string strPersonCode, string strEnBankCardNo, string strBanlance)
        {
            string strWriteResult = "还款计划及临时退款交易订单制定失败！";

            #region 各个对应字段赋值

            string strUnitCode = strDefUnitCode;    //平台编码
            //string strPersonCode = strPersonCode; //用户人员编码

            string strMemberLevelCode = "00";       //会员级别代码

            clsMbrReward myMbr = new clsMbrReward(); //根据人员编码获取会员信息
            DataSet dsLevel = myMbr.GetMemberInfo(strUnitCode, strPersonCode);
            if (dsLevel != null && dsLevel.Tables.Count > 0 && dsLevel.Tables[0].Rows.Count > 0)
            {
                //得到指定ID的当前会员级别代码
                strMemberLevelCode = dsLevel.Tables[0].Rows[0]["MEMBERLEVEL"].ToString();
            }

            string strPlanID = Guid.NewGuid().ToString("N"); //计划ID
            string strPlanType = "POS";                      //计划类型：POS=信用卡代还，ATM=信用卡套现，HBEI=花呗代还     
            string strBankCardNo = strEnBankCardNo;          //银行卡号
            string strPlanAmount = strBanlance;              //还款金额   
            string strCardBalance = strBanlance;             //卡内余额 
            string strPayCity = "310000,310000,310000";      //预设信用卡消费城市     
            string strPlanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //计划制定时间

            #endregion

            #region 因为接口的有效调用时间是07:00至22:00，因此需要对计划交易时间做下分析和处理

            string strCurDate = DateTime.Now.ToString("yyyy-MM-dd"); //当前日期
            string strCurTime = DateTime.Now.ToString("HH:mm:ss");   //当前时间

            string strPlanDateBegin = strCurDate + " 00:00:00"; //计划执行开始时间
            string strPlanDateEnd = strCurDate + " 23:59:59";   //计划执行截至时间
            string strTradeTime = strPlanTime;                  //订单预设交易时间

            //判断当前时间处于哪个时间段之内，做相应的处理
            if (strCurTime.CompareTo("00:00:00") >= 0
                && strCurTime.CompareTo("09:00:00") < 0)
            {
                strTradeTime = strCurDate + " 09:22:16";
            }
            else if (strCurTime.CompareTo("09:00:00") >= 0
                     && strCurTime.CompareTo("21:00:00") < 0)
            {
                //将交易时间设定在晚上 21:30:00 至 22:00:00 之间
                strTradeTime = DateTime.Now.AddMinutes(30).ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                //晚上22:00:00之后接口不提供服务，因此将交易时间预设到第二天执行
                string strTomorrow = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                strPlanDateBegin = strTomorrow + " 00:00:00";
                strPlanDateEnd = strTomorrow + " 23:59:59";
                strTradeTime = strTomorrow + " 09:32:16";
            }

            #endregion

            #region 将字段及其值组合成json数组

            JArray objJArray = new JArray();

            JObject objJObject = new JObject();
            objJObject.Add("UnitCode", strUnitCode);
            objJObject.Add("PersonCode", strPersonCode);
            objJObject.Add("PlanID", strPlanID);
            objJObject.Add("PlanType", strPlanType);
            objJObject.Add("PlanTime", strPlanTime);
            objJObject.Add("BankCardNo", strBankCardNo);
            objJObject.Add("PlanAmount", strPlanAmount);
            objJObject.Add("CardBalance", strCardBalance);
            objJObject.Add("PlanDateBegin", strPlanDateBegin);
            objJObject.Add("PlanDateEnd", strPlanDateEnd);
            objJObject.Add("PayCity", strPayCity);
            objJObject.Add("PlanState", "99"); //00=交易成功，01=交易失败，02=支付中、98=部分成功、99=等待交易
            objJObject.Add("MemberLevel", strMemberLevelCode);
            objJObject.Add("OtherMemo", "");

            objJArray.Add(objJObject);

            //clsRWFile myLog = new clsRWFile(); //将请求结果保存到txt文件中
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", objJArray.ToString(), false);

            #endregion

            #region 向数据库中写入还款计划信息

            //将Json数组转成DataSet
            DataSet dsPlan = clsJConvert.JArryToDataSet(objJArray.ToString());

            clsShare myDict = new clsShare(); //根据人员编码，得到人员ID的值
            string strUserName = myDict.GetNewColValue("Data", "SA_ORG_PERSONINFO", "PERSONCODE", strPersonCode, "PERSONID");

            clsWriteDB myWrite = new clsWriteDB(); //先判断数据是否存在，根据判断结果自动执行insert或者update
            string strKeyColSet = "UnitCode,PersonCode,PlanID"; //重值判断
            string strPlanResult = myWrite.WriteDBNormal_UseSYSCol("Data", "XYK_RepayPlan", strKeyColSet, strUserName, dsPlan);

            #endregion

            #region 向数据库中写入还款交易订单记录（只写入一条记录）

            if (dsPlan != null && dsPlan.Tables.Count > 0 && dsPlan.Tables[0].Rows.Count > 0)
            {
                DataTable dtPlan = dsPlan.Tables[0]; //实例化DataTable
                if (!(strPlanResult.Contains("yooking null"))) //还款计划表insert记录成功
                {
                    //生成一条还款交易订单，交易时间在下午
                    //将用于虚拟账户余额清零的还款交易订单记录写入到后台数据库中
                    bool bPos02Ret = CreateTempHuankuanOrder(strUnitCode, strPersonCode, strPlanID, 
                                      strEnBankCardNo, strTradeTime, strPayCity, Convert.ToDouble(strPlanAmount));

                    if (bPos02Ret) //判断还款定单是否成功写入数据库
                    {
                        strWriteResult = "还款计划及临时退款交易订单制定成功！";
                    }              
                }
            }

            #endregion

            return strWriteResult; //主从表的insert结果
        }

        //注释：王庆文 2020年12月14日===================================================================================
        //生成一条还款交易订单，交易时间在当前时间的30分钟之后
        public bool CreateTempHuankuanOrder(string strUnitCode, string strPersonCode, string strPlanID,
                              string strEnBankCardNo, string strTradeTime, string strPayCityCodSet, double dTradeAmt)
        {
            #region 相对为固定值的基础参数

            //生成平台交易订单号
            Random rd = new Random(); //随机数实例
            int iRandom = rd.Next(100000, 999999); //生成六位随机数
            string strCurTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            //订单号格式示例：POS0220200502225459620954773
            string strPOrderNum = "POS02" + strCurTime + iRandom.ToString();

            //信用卡对应的预留手机号
            clsTradeOrder_New myPlan = new clsTradeOrder_New(); //实例化函数类库
            string strTrMobilePhone = myPlan.GetCreditCardPhone(strUnitCode, strPersonCode, strEnBankCardNo);

            //根据省份代码，判断如果为直辖市，则省份代码即为城市代码
            string strPayCity = strPayCityCodSet; //默认的交易商户所在城市代码
            string strPayProvince = strPayCityCodSet.Substring(0, 6);
            if (strPayProvince == "110000" || strPayProvince == "310000"
                || strPayProvince == "120000" || strPayProvince == "500000")
            {
                strPayCity = strPayProvince; //直接取前六位作为城市代码
            }
            else
            {
                //取中间六位作为城市代码
                strPayCity = strPayCityCodSet.Substring(7, 6);
            }

            //还入金额Y = 卡内余额 - 1.50元笔数费
            double dMoneySum = dTradeAmt - 1.50;

            #endregion

            #region 交易订单表XYK_TradeOrder入库需要的全部字段

            //string strPlanID = strPlanID;                  //计划ID
            string strTradeType = "POS02";                   //交易类型
            string strTradeTo = "02";                        //资金流向，01=支出、02=收入
            //string strPOrderNum = strPOrderNum;            //平台订单号
            string strIOrderNum = strPOrderNum;              //接口订单号
            string strTrBankCardNo = strEnBankCardNo;        //交易银行卡号          
            //string strTrMobilePhone = strTrMobilePhone;    //交易预留手机号
            string strPlanTradeTime = strTradeTime;          //预设交易时间
            string strTradeAmount = dTradeAmt.ToString("0.00"); //交易金额
            string strTradeServiceRate = "0.0000";           //手续费比率
            string strTradeServiceFee = "0.00";              //手续费金额
            string strMemberDiscount = "1";                  //手续费折扣
            string strRealServiceRate = "0.0000";            //实收手续比率
            string strRealServiceFee = "0.00";               //实收手续费
            string strExtraServiceFee = "1.50";              //额外收费金额
            string strMoneySum = dMoneySum.ToString("0.00"); //最终交易金额
            string strAllServiceFee = "1.50";                //服务收费总额
            //string strPayCity = strPayCity;                //预设消费城市
            string strMccList = "";                          //交易MCC码
            string strSeBankCardNo = strEnBankCardNo;        //结算银行卡号
            string strSeMobilePhone = strTrMobilePhone;      //结算预留手机号
            string strInterCallTime = "";                    //接口调用时间
            string strRealTradeTime = "";                    //实际交易时间
            string strRealTradeState = "99";                 //实际交易状态
            string strRealSettTime = "";                     //实际结算时间
            string strRealSettState = "99";                  //实际结算状态
            string strOtherMemo = "";                        //订单交易表中的其他说明

            #endregion

            #region 生成即将写入数据库的json数组

            JArray objJArray = new JArray();
            JObject objJObject = new JObject();
            objJObject.Add("PlanID", strPlanID);
            objJObject.Add("TradeType", strTradeType);
            objJObject.Add("TradeTo", strTradeTo);
            objJObject.Add("POrderNum", strPOrderNum);
            objJObject.Add("IOrderNum", strIOrderNum);
            objJObject.Add("TrBankCardNo", strTrBankCardNo);
            objJObject.Add("TrMobilePhone", strTrMobilePhone);
            objJObject.Add("PlanTradeTime", strPlanTradeTime);
            objJObject.Add("TradeAmount", strTradeAmount);
            objJObject.Add("TradeServiceRate", strTradeServiceRate);
            objJObject.Add("TradeServiceFee", strTradeServiceFee);
            objJObject.Add("MemberDiscount", strMemberDiscount);
            objJObject.Add("RealServiceFee", strRealServiceFee);
            objJObject.Add("RealServiceRate", strRealServiceRate);
            objJObject.Add("ExtraServiceFee", strExtraServiceFee);
            objJObject.Add("AllServiceFee", strAllServiceFee);
            objJObject.Add("MoneySum", strMoneySum);
            objJObject.Add("PayCity", strPayCity);
            objJObject.Add("MccList", strMccList);
            objJObject.Add("SeBankCardNo", strSeBankCardNo);
            objJObject.Add("SeMobilePhone", strSeMobilePhone);
            objJObject.Add("InterCallTime", strInterCallTime);
            objJObject.Add("RealTradeTime", strRealTradeTime);
            objJObject.Add("RealTradeState", strRealTradeState);
            objJObject.Add("RealSettTime", strRealSettTime);
            objJObject.Add("RealSettState", strRealSettState);
            objJObject.Add("OtherMemo", strOtherMemo);

            objJArray.Add(objJObject);

            #endregion

            #region 向数据库中写入交易订单数据

            //clsRWFile myLog = new clsRWFile(); //将请求结果保存到txt文件中
            //myLog.WriteInfoToTxtFile("SysLog", "wqw.txt", objJArray.ToString(), false);

            DataSet dsData = clsJConvert.JArryToDataSet(objJArray.ToString()); //将Json数组转成DataSet

            clsShare myDict = new clsShare(); //根据人员编码，得到人员ID的值
            string strUserName = myDict.GetNewColValue("Data", "SA_ORG_PERSONINFO", "PERSONCODE", strPersonCode, "PERSONID");

            clsWriteDB myWrite = new clsWriteDB(); //先判断数据是否存在，根据判断结果自动执行insert或者update
            string strKeyColSet = "PlanID,PlanTradeTime,TradeAmount"; //重值判断
            string strPos02Result = myWrite.WriteDBNormal_UseSYSCol("Data", "XYK_TradeOrder", strKeyColSet, strUserName, dsData);

            #endregion

            //POS02还款订单记录insert成功
            if (strPos02Result.Contains("yooking null"))
            {
                return false; //失败标记               
            }
            else
            {
                return true; //成功标记
            }
        }

        #endregion






    }
}
